<?php

namespace app\api\controller;

use function AlibabaCloud\Client\env;
use app\common\controller\Api;
use app\common\model\Config;
use app\common\model\FamilyTree;
use app\common\model\PaymentLog;
use think\Db;
use think\Env;
use think\Exception;
use Yansongda\Pay\Pay;
use Yansongda\Pay\Log;

class  WechatPay extends Api
{
    //protected $noNeedLogin = '*';
    protected $noNeedLogin = ['notify'];
    protected $noNeedRight = '*';

    protected $config = [
        'appid' => 'wx4b24b839584a9262', // APP APPID
        'app_id' => 'wx696e13aac723a1dc', // 公众号 APPID
        'miniapp_id' => 'wxb3fxxxxxxxxxxx', // 小程序 APPID
        'mch_id' => '1594359441',
        'key' => 'afd0579a772ce27c270b677cffe07c1c',
        'notify_url' => 'http://yanda.net.cn/notify.php',
        'cert_client' => './cert/apiclient_cert.pem', // optional，退款等情况时用到
        'cert_key' => './cert/apiclient_key.pem',// optional，退款等情况时用到
        'log' => [ // optional
                   'file' => '../logs/wechat.log',
                   'level' => 'info', // 建议生产环境等级调整为 info，开发环境为 debug
                   'type' => 'single', // optional, 可选 daily.
                   'max_file' => 30, // optional, 当 type 为 daily 时有效，默认 30 天
        ],
        'http' => [ // optional
                    'timeout' => 5.0,
                    'connect_timeout' => 5.0,
                    // 更多配置项请参考 [Guzzle](https://guzzle-cn.readthedocs.io/zh_CN/latest/request-options.html)
        ],
        //'mode' => 'dev', // optional, dev/hk;当为 `hk` 时，为香港 gateway。
    ];


    public function send($order,$payment){
        switch($payment){
            case 'web':
                $alipay = Pay::wechat($this->config)->scan($order);
                break;
            case 'wap':
                $alipay = Pay::wechat($this->config)->wap($order);
                break;
            case 'app':
                $alipay = Pay::wechat($this->config)->app($order);
                break;
            default:
                $alipay = Pay::wechat($this->config)->web($order);
                break;
        }
        $send = $alipay->getContent();
        return $send;
        //return $alipay;
        //return $alipay->send();
    }

    public function notify()
    {
        //$pay = Pay::wechat($this->config);
        write_log(var_export($_POST,true),'微信支付参数');
        try{
            //这是签名验证串，在 App配置 查询或重置
            $secretKey = Env::get('pay.pay_secret');
            //发送通知时的 Unix 时间戳，可用于处理通知过期策略
            $timestamp = intval($_POST["timestamp"]);
            //假定15分钟内有效
            if (($timestamp + 15 * 60) < date_timestamp_get(date_create())) {
                //通知已过期
                throw new Exception('通知过期');
            }
            $kv = array();
            //遍历 form 表单
            foreach ($_POST as $key => $val) {
                $kv[$key] = $val;
            }
            ksort($kv);
            reset($kv);
            $param = '';
            foreach ($kv AS $key => $val) {
                if ($key != 'sign') {
                    $param .= "$key=$val&";
                }
            }
            $param = substr($param, 0, -1).$secretKey;
            $verify_result = (md5($param) == strtolower($kv["sign"]));
            if ($verify_result) {
                //获取有效的参数值
                $info = PaymentLog::where('pay_no',$kv['orderid'])->where('status',0)->find();
                if(empty($info)){
                    $a =  Db::connect('db_config2')->name('ewei_shop_order')->where('ordersn',$kv['orderid'])->find();
                    if(empty($a)){
                        throw new Exception('订单不存在');
                    }else{
                        Db::connect('db_config2')->name('ewei_shop_order')->where('ordersn',$kv['orderid'])->update(['status'=>1]);
                    }
                }else{
                    if($info['money'] != $kv['amount']){
                        throw new Exception('金额不正确');
                    }
                    if($info['types'] == 1){
                        $rate = Config::getValue('recharge_rate','family_tree');
                        \app\common\model\User::setMoney($info['user_id'],'money',$info['money']*$rate,'6000','充值',$info['pay_no']);

                    }else{
                        FamilyTree::where('id',$info['f_id'])->setInc('liufang',$info['money']);
                        FamilyTree::where('id',$info['f_id'])->setInc('shengyv',$info['money'] * 365);
                        \app\common\model\User::liufangJl($info['money'],$info['f_id']);
                    }
                    PaymentLog::where('id',$info['id'])->update(['status'=>1]);
                }
                echo "OK";
            } else {
                //签名验证失败
                throw new Exception('签名错误');
            }
            exit();
            //Log::debug('Wechat notify', $data->all());
        } catch (\Exception $e) {
            // $e->getMessage();
            write_log($e->getMessage(),'微信支付错误');
            exit();
        }
    }
}